﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using IT.CMS.Web.Areas.Administration.Models.Common;
using IT.CMS.Web.Areas.Administration.Models.Settings;
using IT.CMS.Web.Areas.Administration.Models.Sites;
using IT.CMS.Core;
using IT.CMS.Core.Domain;
using IT.CMS.Core.Domain.Blogs;
using IT.CMS.Core.Domain.Catalog;
using IT.CMS.Core.Domain.Common;
using IT.CMS.Core.Domain.Customers;
using IT.CMS.Core.Domain.Directory;
using IT.CMS.Core.Domain.Forums;
using IT.CMS.Core.Domain.Localization;
using IT.CMS.Core.Domain.Media;
using IT.CMS.Core.Domain.News;
using IT.CMS.Core.Domain.Orders;
using IT.CMS.Core.Domain.Security;
using IT.CMS.Core.Domain.Seo;
using IT.CMS.Core.Domain.Shipping;
using IT.CMS.Core.Domain.Tax;
using IT.CMS.Services.Common;
using IT.CMS.Services.Configuration;
using IT.CMS.Services.Customers;
using IT.CMS.Services.Directory;
using IT.CMS.Services.Helpers;
using IT.CMS.Services.Localization;
using IT.CMS.Services.Logging;
using IT.CMS.Services.Media;
using IT.CMS.Services.Orders;
using IT.CMS.Services.Security;
using IT.CMS.Services.Sites;
using IT.CMS.Services.Tax;
using IT.CMS.Web.Framework;
using IT.CMS.Web.Framework.Controllers;
using IT.CMS.Web.Framework.Localization;
using IT.CMS.Web.Framework.Themes;
using IT.CMS.Web.Framework.UI.Captcha;
using Telerik.Web.Mvc;

namespace IT.CMS.Web.Areas.Administration.Controllers
{
	[AdminAuthorize]
    public partial class SettingController : BaseCmsController
	{
		#region Fields

        private readonly ISettingService _settingService;
        private readonly ICountryService _countryService;
        private readonly IStateProvinceService _stateProvinceService;
        private readonly IAddressService _addressService;
        private readonly ITaxCategoryService _taxCategoryService;
        private readonly ICurrencyService _currencyService;
        private readonly IPictureService _pictureService;
        private readonly ILocalizationService _localizationService;
        private readonly IDateTimeHelper _dateTimeHelper;
        private readonly IOrderService _orderService;
        private readonly IEncryptionService _encryptionService;
        private readonly IThemeProvider _themeProvider;
        private readonly ICustomerService _customerService;
        private readonly ICustomerActivityService _customerActivityService;
        private readonly IPermissionService _permissionService;
        private readonly IWebHelper _webHelper;
        private readonly IFulltextService _fulltextService;
        private readonly IMaintenanceService _maintenanceService;
        private readonly ISiteService _siteService;
        private readonly IWorkContext _workContext;
        private readonly IGenericAttributeService _genericAttributeService;

		#endregion

		#region Constructors

        public SettingController(ISettingService settingService,
            ICountryService countryService, IStateProvinceService stateProvinceService,
            IAddressService addressService, ITaxCategoryService taxCategoryService,
            ICurrencyService currencyService, IPictureService pictureService, 
            ILocalizationService localizationService, IDateTimeHelper dateTimeHelper,
            IOrderService orderService, IEncryptionService encryptionService,
            IThemeProvider themeProvider, ICustomerService customerService, 
            ICustomerActivityService customerActivityService, IPermissionService permissionService,
            IWebHelper webHelper, IFulltextService fulltextService, 
            IMaintenanceService maintenanceService, ISiteService siteService,
            IWorkContext workContext, IGenericAttributeService genericAttributeService)
        {
            this._settingService = settingService;
            this._countryService = countryService;
            this._stateProvinceService = stateProvinceService;
            this._addressService = addressService;
            this._taxCategoryService = taxCategoryService;
            this._currencyService = currencyService;
            this._pictureService = pictureService;
            this._localizationService = localizationService;
            this._dateTimeHelper = dateTimeHelper;
            this._orderService = orderService;
            this._encryptionService = encryptionService;
            this._themeProvider = themeProvider;
            this._customerService = customerService;
            this._customerActivityService = customerActivityService;
            this._permissionService = permissionService;
            this._webHelper = webHelper;
            this._fulltextService = fulltextService;
            this._maintenanceService = maintenanceService;
            this._siteService = siteService;
            this._workContext = workContext;
            this._genericAttributeService = genericAttributeService;
        }

		#endregion 
        
        #region Methods
        
        [ChildActionOnly]
        public ActionResult SiteScopeConfiguration()
        {
            var allSites = _siteService.GetAllSites();
            if (allSites.Count < 2)
                return Content("");

            var model = new SiteScopeConfigurationModel();
            foreach (var s in allSites)
            {
                model.Sites.Add(new SiteModel()
                {
                    Id = s.Id,
                    Name = s.Name
                });
            }
            model.SiteId = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);

            return PartialView(model);
        }


        public ActionResult ChangeSiteScopeConfiguration(int siteid, string returnUrl = "")
        {
            var site = _siteService.GetSiteById(siteid);
            if (site != null || siteid == 0)
            {
                _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
                    SystemCustomerAttributeNames.AdminAreaSiteScopeConfiguration, siteid);
            }
            //url referrer
            if (String.IsNullOrEmpty(returnUrl))
                returnUrl = _webHelper.GetUrlReferrer();
            //home page
            if (String.IsNullOrEmpty(returnUrl))
                returnUrl = Url.Action("Index", "Home");
            return Redirect(returnUrl);
        }

        public ActionResult Blog()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var blogSettings = _settingService.LoadSetting<BlogSettings>(siteScope);
            var model = blogSettings.ToModel();
            model.ActiveSiteScopeConfiguration = siteScope;
            if (siteScope > 0)
            {
                model.Enabled_OverrideForSite = _settingService.SettingExists(blogSettings, x => x.Enabled, siteScope);
                model.PostsPageSize_OverrideForSite = _settingService.SettingExists(blogSettings, x => x.PostsPageSize, siteScope);
                model.AllowNotRegisteredUsersToLeaveComments_OverrideForSite = _settingService.SettingExists(blogSettings, x => x.AllowNotRegisteredUsersToLeaveComments, siteScope);
                model.NotifyAboutNewBlogComments_OverrideForSite = _settingService.SettingExists(blogSettings, x => x.NotifyAboutNewBlogComments, siteScope);
                model.NumberOfTags_OverrideForSite = _settingService.SettingExists(blogSettings, x => x.NumberOfTags, siteScope);
                model.ShowHeaderRssUrl_OverrideForSite = _settingService.SettingExists(blogSettings, x => x.ShowHeaderRssUrl, siteScope);
            }

            return View(model);
        }
        
        [HttpPost]
        public ActionResult Blog(BlogSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var blogSettings = _settingService.LoadSetting<BlogSettings>(siteScope);
            blogSettings = model.ToEntity(blogSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            if (model.Enabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(blogSettings, x => x.Enabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(blogSettings, x => x.Enabled, siteScope);
            
            if (model.PostsPageSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(blogSettings, x => x.PostsPageSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(blogSettings, x => x.PostsPageSize, siteScope);
            
            if (model.AllowNotRegisteredUsersToLeaveComments_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(blogSettings, x => x.AllowNotRegisteredUsersToLeaveComments, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(blogSettings, x => x.AllowNotRegisteredUsersToLeaveComments, siteScope);
            
            if (model.NotifyAboutNewBlogComments_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(blogSettings, x => x.NotifyAboutNewBlogComments, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(blogSettings, x => x.NotifyAboutNewBlogComments, siteScope);
            
            if (model.NumberOfTags_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(blogSettings, x => x.NumberOfTags, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(blogSettings, x => x.NumberOfTags, siteScope);
            
            if (model.ShowHeaderRssUrl_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(blogSettings, x => x.ShowHeaderRssUrl, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(blogSettings, x => x.ShowHeaderRssUrl, siteScope);
            
            //now clear settings cache
            _settingService.ClearCache();

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("Blog");
        }




        public ActionResult Forum()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var forumSettings = _settingService.LoadSetting<ForumSettings>(siteScope);
            var model = forumSettings.ToModel();
            model.ActiveSiteScopeConfiguration = siteScope;
            if (siteScope > 0)
            {
                model.ForumsEnabled_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.ForumsEnabled, siteScope);
                model.RelativeDateTimeFormattingEnabled_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.RelativeDateTimeFormattingEnabled, siteScope);
                model.ShowCustomersPostCount_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.ShowCustomersPostCount, siteScope);
                model.AllowGuestsToCreatePosts_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.AllowGuestsToCreatePosts, siteScope);
                model.AllowGuestsToCreateTopics_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.AllowGuestsToCreateTopics, siteScope);
                model.AllowCustomersToEditPosts_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.AllowCustomersToEditPosts, siteScope);
                model.AllowCustomersToDeletePosts_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.AllowCustomersToDeletePosts, siteScope);
                model.AllowCustomersToManageSubscriptions_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.AllowCustomersToManageSubscriptions, siteScope);
                model.TopicsPageSize_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.TopicsPageSize, siteScope);
                model.PostsPageSize_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.PostsPageSize, siteScope);
                model.ForumEditor_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.ForumEditor, siteScope);
                model.SignaturesEnabled_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.SignaturesEnabled, siteScope);
                model.AllowPrivateMessages_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.AllowPrivateMessages, siteScope);
                model.ShowAlertForPM_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.ShowAlertForPM, siteScope);
                model.NotifyAboutPrivateMessages_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.NotifyAboutPrivateMessages, siteScope);
                model.ActiveDiscussionsFeedEnabled_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.ActiveDiscussionsFeedEnabled, siteScope);
                model.ActiveDiscussionsFeedCount_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.ActiveDiscussionsFeedCount, siteScope);
                model.ForumFeedsEnabled_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.ForumFeedsEnabled, siteScope);
                model.ForumFeedCount_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.ForumFeedCount, siteScope);
                model.SearchResultsPageSize_OverrideForSite = _settingService.SettingExists(forumSettings, x => x.SearchResultsPageSize, siteScope);
            }
            model.ForumEditorValues = forumSettings.ForumEditor.ToSelectList();

            return View(model);
        }
        [HttpPost]
        public ActionResult Forum(ForumSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var forumSettings = _settingService.LoadSetting<ForumSettings>(siteScope);
            forumSettings = model.ToEntity(forumSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            if (model.ForumsEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.ForumsEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.ForumsEnabled, siteScope);
            
            if (model.RelativeDateTimeFormattingEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.RelativeDateTimeFormattingEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.RelativeDateTimeFormattingEnabled, siteScope);
            
            if (model.ShowCustomersPostCount_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.ShowCustomersPostCount, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.ShowCustomersPostCount, siteScope);
            
            if (model.AllowGuestsToCreatePosts_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.AllowGuestsToCreatePosts, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.AllowGuestsToCreatePosts, siteScope);
            
            if (model.AllowGuestsToCreateTopics_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.AllowGuestsToCreateTopics, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.AllowGuestsToCreateTopics, siteScope);
            
            if (model.AllowCustomersToEditPosts_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.AllowCustomersToEditPosts, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.AllowCustomersToEditPosts, siteScope);
            
            if (model.AllowCustomersToDeletePosts_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.AllowCustomersToDeletePosts, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.AllowCustomersToDeletePosts, siteScope);
            
            if (model.AllowCustomersToManageSubscriptions_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.AllowCustomersToManageSubscriptions, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.AllowCustomersToManageSubscriptions, siteScope);
            
            if (model.TopicsPageSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.TopicsPageSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.TopicsPageSize, siteScope);
            
            if (model.PostsPageSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.PostsPageSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.PostsPageSize, siteScope);
            
            if (model.ForumEditor_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.ForumEditor, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.ForumEditor, siteScope);
            
            if (model.SignaturesEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.SignaturesEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.SignaturesEnabled, siteScope);
            
            if (model.SignaturesEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.SignaturesEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.SignaturesEnabled, siteScope);
            
            if (model.AllowPrivateMessages_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.AllowPrivateMessages, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.AllowPrivateMessages, siteScope);
            
            if (model.ShowAlertForPM_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.ShowAlertForPM, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.ShowAlertForPM, siteScope);
            
            if (model.NotifyAboutPrivateMessages_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.NotifyAboutPrivateMessages, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.NotifyAboutPrivateMessages, siteScope);
            
            if (model.ActiveDiscussionsFeedEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.ActiveDiscussionsFeedEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.ActiveDiscussionsFeedEnabled, siteScope);
            
            if (model.ActiveDiscussionsFeedCount_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.ActiveDiscussionsFeedCount, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.ActiveDiscussionsFeedCount, siteScope);
            
            if (model.ForumFeedsEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.ForumFeedsEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.ForumFeedsEnabled, siteScope);
            
            if (model.ForumFeedCount_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.ForumFeedCount, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.ForumFeedCount, siteScope);
            
            if (model.SearchResultsPageSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(forumSettings, x => x.SearchResultsPageSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(forumSettings, x => x.SearchResultsPageSize, siteScope);
            
            //now clear settings cache
            _settingService.ClearCache();

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("Forum");
        }




        public ActionResult News()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var newsSettings = _settingService.LoadSetting<NewsSettings>(siteScope);
            var model = newsSettings.ToModel();
            model.ActiveSiteScopeConfiguration = siteScope;
            if (siteScope > 0)
            {
                model.Enabled_OverrideForSite = _settingService.SettingExists(newsSettings, x => x.Enabled, siteScope);
                model.AllowNotRegisteredUsersToLeaveComments_OverrideForSite = _settingService.SettingExists(newsSettings, x => x.AllowNotRegisteredUsersToLeaveComments, siteScope);
                model.NotifyAboutNewNewsComments_OverrideForSite = _settingService.SettingExists(newsSettings, x => x.NotifyAboutNewNewsComments, siteScope);
                model.ShowNewsOnMainPage_OverrideForSite = _settingService.SettingExists(newsSettings, x => x.ShowNewsOnMainPage, siteScope);
                model.MainPageNewsCount_OverrideForSite = _settingService.SettingExists(newsSettings, x => x.MainPageNewsCount, siteScope);
                model.NewsArchivePageSize_OverrideForSite = _settingService.SettingExists(newsSettings, x => x.NewsArchivePageSize, siteScope);
                model.ShowHeaderRssUrl_OverrideForSite = _settingService.SettingExists(newsSettings, x => x.ShowHeaderRssUrl, siteScope);
            }
            return View(model);
        }
        [HttpPost]
        public ActionResult News(NewsSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var newsSettings = _settingService.LoadSetting<NewsSettings>(siteScope);
            newsSettings = model.ToEntity(newsSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            if (model.Enabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(newsSettings, x => x.Enabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(newsSettings, x => x.Enabled, siteScope);

            if (model.AllowNotRegisteredUsersToLeaveComments_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(newsSettings, x => x.AllowNotRegisteredUsersToLeaveComments, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(newsSettings, x => x.AllowNotRegisteredUsersToLeaveComments, siteScope);

            if (model.NotifyAboutNewNewsComments_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(newsSettings, x => x.NotifyAboutNewNewsComments, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(newsSettings, x => x.NotifyAboutNewNewsComments, siteScope);

            if (model.ShowNewsOnMainPage_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(newsSettings, x => x.ShowNewsOnMainPage, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(newsSettings, x => x.ShowNewsOnMainPage, siteScope);

            if (model.MainPageNewsCount_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(newsSettings, x => x.MainPageNewsCount, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(newsSettings, x => x.MainPageNewsCount, siteScope);

            if (model.NewsArchivePageSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(newsSettings, x => x.NewsArchivePageSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(newsSettings, x => x.NewsArchivePageSize, siteScope);

            if (model.ShowHeaderRssUrl_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(newsSettings, x => x.ShowHeaderRssUrl, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(newsSettings, x => x.ShowHeaderRssUrl, siteScope);

            //now clear settings cache
            _settingService.ClearCache();


            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("News");
        }




        public ActionResult Shipping()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var shippingSettings = _settingService.LoadSetting<ShippingSettings>(siteScope);
            var model = shippingSettings.ToModel();
            model.ActiveSiteScopeConfiguration = siteScope;
            if (siteScope > 0)
            {
                model.FreeShippingOverXEnabled_OverrideForSite = _settingService.SettingExists(shippingSettings, x => x.FreeShippingOverXEnabled, siteScope);
                model.FreeShippingOverXValue_OverrideForSite = _settingService.SettingExists(shippingSettings, x => x.FreeShippingOverXValue, siteScope);
                model.FreeShippingOverXIncludingTax_OverrideForSite = _settingService.SettingExists(shippingSettings, x => x.FreeShippingOverXIncludingTax, siteScope);
                model.EstimateShippingEnabled_OverrideForSite = _settingService.SettingExists(shippingSettings, x => x.EstimateShippingEnabled, siteScope);
                model.DisplayShipmentEventsToCustomers_OverrideForSite = _settingService.SettingExists(shippingSettings, x => x.DisplayShipmentEventsToCustomers, siteScope);
                model.ShippingOriginAddress_OverrideForSite = _settingService.SettingExists(shippingSettings, x => x.ShippingOriginAddressId, siteScope);
            }
            //shipping origin
            var originAddress = shippingSettings.ShippingOriginAddressId > 0
                                     ? _addressService.GetAddressById(shippingSettings.ShippingOriginAddressId)
                                     : null;
            if (originAddress != null)
                model.ShippingOriginAddress = originAddress.ToModel();
            else
                model.ShippingOriginAddress = new AddressModel();

            model.ShippingOriginAddress.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0" });
            foreach (var c in _countryService.GetAllCountries(true))
                model.ShippingOriginAddress.AvailableCountries.Add(new SelectListItem() { Text = c.Name, Value = c.Id.ToString(), Selected = (originAddress != null && c.Id == originAddress.CountryId) });

            var states = originAddress != null && originAddress.Country != null ? _stateProvinceService.GetStateProvincesByCountryId(originAddress.Country.Id, true).ToList() : new List<StateProvince>();
            if (states.Count > 0)
            {
                foreach (var s in states)
                    model.ShippingOriginAddress.AvailableStates.Add(new SelectListItem() { Text = s.Name, Value = s.Id.ToString(), Selected = (s.Id == originAddress.StateProvinceId) });
            }
            else
                model.ShippingOriginAddress.AvailableStates.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = "0" });
            model.ShippingOriginAddress.CountryEnabled = true;
            model.ShippingOriginAddress.StateProvinceEnabled = true;
            model.ShippingOriginAddress.ZipPostalCodeEnabled = true;
            model.ShippingOriginAddress.ZipPostalCodeRequired = true;
            
            return View(model);
        }
        [HttpPost]
        public ActionResult Shipping(ShippingSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var shippingSettings = _settingService.LoadSetting<ShippingSettings>(siteScope);
            shippingSettings = model.ToEntity(shippingSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            if (model.FreeShippingOverXEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shippingSettings, x => x.FreeShippingOverXEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shippingSettings, x => x.FreeShippingOverXEnabled, siteScope);

            if (model.FreeShippingOverXValue_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shippingSettings, x => x.FreeShippingOverXValue, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shippingSettings, x => x.FreeShippingOverXValue, siteScope);

            if (model.FreeShippingOverXIncludingTax_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shippingSettings, x => x.FreeShippingOverXIncludingTax, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shippingSettings, x => x.FreeShippingOverXIncludingTax, siteScope);

            if (model.EstimateShippingEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shippingSettings, x => x.EstimateShippingEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shippingSettings, x => x.EstimateShippingEnabled, siteScope);

            if (model.DisplayShipmentEventsToCustomers_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shippingSettings, x => x.DisplayShipmentEventsToCustomers, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shippingSettings, x => x.DisplayShipmentEventsToCustomers, siteScope);

            if (model.ShippingOriginAddress_OverrideForSite || siteScope == 0)
            {
                //update address
                var addressId = _settingService.SettingExists(shippingSettings, x => x.ShippingOriginAddressId, siteScope) ?
                    shippingSettings.ShippingOriginAddressId : 0;
                var originAddress = _addressService.GetAddressById(addressId) ??
                    new Core.Domain.Common.Address()
                    {
                        CreatedOnUtc = DateTime.UtcNow,
                    };
                //update ID manually (in case we're in multi-site configuration mode it'll be set to the shared one)
                model.ShippingOriginAddress.Id = addressId;
                originAddress = model.ShippingOriginAddress.ToEntity(originAddress);
                if (originAddress.Id > 0)
                    _addressService.UpdateAddress(originAddress);
                else
                    _addressService.InsertAddress(originAddress);
                shippingSettings.ShippingOriginAddressId = originAddress.Id;

                _settingService.SaveSetting(shippingSettings, x => x.ShippingOriginAddressId, siteScope, false);
            }
            else if (siteScope > 0)
                _settingService.DeleteSetting(shippingSettings, x => x.ShippingOriginAddressId, siteScope);


            //now clear settings cache
            _settingService.ClearCache();


            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("Shipping");
        }




        public ActionResult Tax()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var taxSettings = _settingService.LoadSetting<TaxSettings>(siteScope);
            var model = taxSettings.ToModel();
            model.ActiveSiteScopeConfiguration = siteScope;
            if (siteScope > 0)
            {
                model.PricesIncludeTax_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.PricesIncludeTax, siteScope);
                model.AllowCustomersToSelectTaxDisplayType_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.AllowCustomersToSelectTaxDisplayType, siteScope);
                model.TaxDisplayType_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.TaxDisplayType, siteScope);
                model.DisplayTaxSuffix_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.DisplayTaxSuffix, siteScope);
                model.DisplayTaxRates_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.DisplayTaxRates, siteScope);
                model.HideZeroTax_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.HideZeroTax, siteScope);
                model.HideTaxInOrderSummary_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.HideTaxInOrderSummary, siteScope);
                model.TaxBasedOn_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.TaxBasedOn, siteScope);
                model.DefaultTaxAddress_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.DefaultTaxAddressId, siteScope);
                model.ShippingIsTaxable_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.ShippingIsTaxable, siteScope);
                model.ShippingPriceIncludesTax_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.ShippingPriceIncludesTax, siteScope);
                model.ShippingTaxClassId_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.ShippingTaxClassId, siteScope);
                model.PaymentMethodAdditionalFeeIsTaxable_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.PaymentMethodAdditionalFeeIsTaxable, siteScope);
                model.PaymentMethodAdditionalFeeIncludesTax_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.PaymentMethodAdditionalFeeIncludesTax, siteScope);
                model.PaymentMethodAdditionalFeeTaxClassId_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.PaymentMethodAdditionalFeeTaxClassId, siteScope);
                model.EuVatEnabled_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.EuVatEnabled, siteScope);
                model.EuVatShopCountryId_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.EuVatShopCountryId, siteScope);
                model.EuVatAllowVatExemption_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.EuVatAllowVatExemption, siteScope);
                model.EuVatUseWebService_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.EuVatUseWebService, siteScope);
                model.EuVatEmailAdminWhenNewVatSubmitted_OverrideForSite = _settingService.SettingExists(taxSettings, x => x.EuVatEmailAdminWhenNewVatSubmitted, siteScope);
            }

            model.TaxBasedOnValues = taxSettings.TaxBasedOn.ToSelectList();
            model.TaxDisplayTypeValues = taxSettings.TaxDisplayType.ToSelectList();

            //tax categories
            var taxCategories = _taxCategoryService.GetAllTaxCategories();
            model.ShippingTaxCategories.Add(new SelectListItem() { Text = "---", Value = "0" });
            foreach (var tc in taxCategories)
                model.ShippingTaxCategories.Add(new SelectListItem() { Text = tc.Name, Value = tc.Id.ToString(), Selected = tc.Id == taxSettings.ShippingTaxClassId });
            model.PaymentMethodAdditionalFeeTaxCategories.Add(new SelectListItem() { Text = "---", Value = "0" });
            foreach (var tc in taxCategories)
                model.PaymentMethodAdditionalFeeTaxCategories.Add(new SelectListItem() { Text = tc.Name, Value = tc.Id.ToString(), Selected = tc.Id == taxSettings.PaymentMethodAdditionalFeeTaxClassId });

            //EU VAT countries
            model.EuVatShopCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0" });
            foreach (var c in _countryService.GetAllCountries(true))
                model.EuVatShopCountries.Add(new SelectListItem() { Text = c.Name, Value = c.Id.ToString(), Selected = c.Id == taxSettings.EuVatShopCountryId });

            //default tax address
            var defaultAddress = taxSettings.DefaultTaxAddressId > 0
                                     ? _addressService.GetAddressById(taxSettings.DefaultTaxAddressId)
                                     : null;
            if (defaultAddress != null)
                model.DefaultTaxAddress = defaultAddress.ToModel();
            else
                model.DefaultTaxAddress = new AddressModel();

            model.DefaultTaxAddress.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0" });
            foreach (var c in _countryService.GetAllCountries(true))
                model.DefaultTaxAddress.AvailableCountries.Add(new SelectListItem() { Text = c.Name, Value = c.Id.ToString(), Selected = (defaultAddress != null && c.Id == defaultAddress.CountryId) });

            var states = defaultAddress != null && defaultAddress.Country != null ? _stateProvinceService.GetStateProvincesByCountryId(defaultAddress.Country.Id, true).ToList() : new List<StateProvince>();
            if (states.Count > 0)
            {
                foreach (var s in states)
                    model.DefaultTaxAddress.AvailableStates.Add(new SelectListItem() { Text = s.Name, Value = s.Id.ToString(), Selected = (s.Id == defaultAddress.StateProvinceId) });
            }
            else
                model.DefaultTaxAddress.AvailableStates.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = "0" });
            model.DefaultTaxAddress.CountryEnabled = true;
            model.DefaultTaxAddress.StateProvinceEnabled = true;
            model.DefaultTaxAddress.ZipPostalCodeEnabled = true;
            model.DefaultTaxAddress.ZipPostalCodeRequired = true;

            return View(model);
        }
        [HttpPost]
        public ActionResult Tax(TaxSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var taxSettings = _settingService.LoadSetting<TaxSettings>(siteScope);
            taxSettings = model.ToEntity(taxSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            if (model.PricesIncludeTax_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.PricesIncludeTax, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.PricesIncludeTax, siteScope);
            
            if (model.AllowCustomersToSelectTaxDisplayType_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.AllowCustomersToSelectTaxDisplayType, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.AllowCustomersToSelectTaxDisplayType, siteScope);
            
            if (model.TaxDisplayType_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.TaxDisplayType, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.TaxDisplayType, siteScope);
            
            if (model.DisplayTaxSuffix_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.DisplayTaxSuffix, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.DisplayTaxSuffix, siteScope);
            
            if (model.DisplayTaxRates_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.DisplayTaxRates, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.DisplayTaxRates, siteScope);
            
            if (model.HideZeroTax_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.HideZeroTax, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.HideZeroTax, siteScope);
            
            if (model.HideTaxInOrderSummary_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.HideTaxInOrderSummary, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.HideTaxInOrderSummary, siteScope);
            
            if (model.TaxBasedOn_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.TaxBasedOn, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.TaxBasedOn, siteScope);



            if (model.DefaultTaxAddress_OverrideForSite || siteScope == 0)
            {
                //update address
                var addressId = _settingService.SettingExists(taxSettings, x => x.DefaultTaxAddressId, siteScope) ?
                    taxSettings.DefaultTaxAddressId : 0;
                var originAddress = _addressService.GetAddressById(addressId) ??
                    new Core.Domain.Common.Address()
                    {
                        CreatedOnUtc = DateTime.UtcNow,
                    };
                //update ID manually (in case we're in multi-site configuration mode it'll be set to the shared one)
                model.DefaultTaxAddress.Id = addressId;
                originAddress = model.DefaultTaxAddress.ToEntity(originAddress);
                if (originAddress.Id > 0)
                    _addressService.UpdateAddress(originAddress);
                else
                    _addressService.InsertAddress(originAddress);
                taxSettings.DefaultTaxAddressId = originAddress.Id;

                _settingService.SaveSetting(taxSettings, x => x.DefaultTaxAddressId, siteScope, false);
            }
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.DefaultTaxAddressId, siteScope);




            if (model.ShippingIsTaxable_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.ShippingIsTaxable, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.ShippingIsTaxable, siteScope);
            
            if (model.ShippingPriceIncludesTax_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.ShippingPriceIncludesTax, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.ShippingPriceIncludesTax, siteScope);
            
            if (model.ShippingTaxClassId_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.ShippingTaxClassId, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.ShippingTaxClassId, siteScope);
            
            if (model.PaymentMethodAdditionalFeeIsTaxable_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.PaymentMethodAdditionalFeeIsTaxable, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.PaymentMethodAdditionalFeeIsTaxable, siteScope);
            
            if (model.PaymentMethodAdditionalFeeIncludesTax_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.PaymentMethodAdditionalFeeIncludesTax, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.PaymentMethodAdditionalFeeIncludesTax, siteScope);
            
            if (model.PaymentMethodAdditionalFeeTaxClassId_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.PaymentMethodAdditionalFeeTaxClassId, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.PaymentMethodAdditionalFeeTaxClassId, siteScope);
            
            if (model.EuVatEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.EuVatEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.EuVatEnabled, siteScope);
            
            if (model.EuVatShopCountryId_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.EuVatShopCountryId, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.EuVatShopCountryId, siteScope);
            
            if (model.EuVatAllowVatExemption_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.EuVatAllowVatExemption, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.EuVatAllowVatExemption, siteScope);

            if (model.EuVatUseWebService_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.EuVatUseWebService, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.EuVatUseWebService, siteScope);

            if (model.EuVatEmailAdminWhenNewVatSubmitted_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(taxSettings, x => x.EuVatEmailAdminWhenNewVatSubmitted, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(taxSettings, x => x.EuVatEmailAdminWhenNewVatSubmitted, siteScope);

            //now clear settings cache
            _settingService.ClearCache();

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("Tax");
        }




        public ActionResult Catalog()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var catalogSettings = _settingService.LoadSetting<CatalogSettings>(siteScope);
            var model = catalogSettings.ToModel();
            model.ActiveSiteScopeConfiguration = siteScope;
            if (siteScope > 0)
            {
                model.ShowProductSku_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ShowProductSku, siteScope);
                model.ShowManufacturerPartNumber_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ShowManufacturerPartNumber, siteScope);
                model.ShowGtin_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ShowGtin, siteScope);
                model.AllowProductSorting_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.AllowProductSorting, siteScope);
                model.AllowProductViewModeChanging_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.AllowProductViewModeChanging, siteScope);
                model.ShowProductsFromSubcategories_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ShowProductsFromSubcategories, siteScope);
                model.ShowCategoryProductNumber_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ShowCategoryProductNumber, siteScope);
                model.ShowCategoryProductNumberIncludingSubcategories_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ShowCategoryProductNumberIncludingSubcategories, siteScope);
                model.CategoryBreadcrumbEnabled_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.CategoryBreadcrumbEnabled, siteScope);
                model.ShowShareButton_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ShowShareButton, siteScope);
                model.ProductReviewsMustBeApproved_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ProductReviewsMustBeApproved, siteScope);
                model.AllowAnonymousUsersToReviewProduct_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.AllowAnonymousUsersToReviewProduct, siteScope);
                model.NotifySiteOwnerAboutNewProductReviews_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.NotifySiteOwnerAboutNewProductReviews, siteScope);
                model.EmailAFriendEnabled_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.EmailAFriendEnabled, siteScope);
                model.AllowAnonymousUsersToEmailAFriend_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.AllowAnonymousUsersToEmailAFriend, siteScope);
                model.RecentlyViewedProductsNumber_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.RecentlyViewedProductsNumber, siteScope);
                model.RecentlyViewedProductsEnabled_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.RecentlyViewedProductsEnabled, siteScope);
                model.RecentlyAddedProductsNumber_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.RecentlyAddedProductsNumber, siteScope);
                model.RecentlyAddedProductsEnabled_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.RecentlyAddedProductsEnabled, siteScope);
                model.CompareProductsEnabled_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.CompareProductsEnabled, siteScope);
                model.ShowBestsellersOnHomepage_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ShowBestsellersOnHomepage, siteScope);
                model.NumberOfBestsellersOnHomepage_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.NumberOfBestsellersOnHomepage, siteScope);
                model.SearchPageProductsPerPage_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.SearchPageProductsPerPage, siteScope);
                model.ProductSearchAutoCompleteEnabled_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ProductSearchAutoCompleteEnabled, siteScope);
                model.ProductSearchAutoCompleteNumberOfProducts_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ProductSearchAutoCompleteNumberOfProducts, siteScope);
                model.ShowProductImagesInSearchAutoComplete_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ShowProductImagesInSearchAutoComplete, siteScope);
                model.ProductsAlsoPurchasedEnabled_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ProductsAlsoPurchasedEnabled, siteScope);
                model.ProductsAlsoPurchasedNumber_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ProductsAlsoPurchasedNumber, siteScope);
                model.EnableDynamicPriceUpdate_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.EnableDynamicPriceUpdate, siteScope);
                model.NumberOfProductTags_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.NumberOfProductTags, siteScope);
                model.ProductsByTagPageSize_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ProductsByTagPageSize, siteScope);
                model.ProductsByTagAllowCustomersToSelectPageSize_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ProductsByTagAllowCustomersToSelectPageSize, siteScope);
                model.ProductsByTagPageSizeOptions_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ProductsByTagPageSizeOptions, siteScope);
                model.IncludeShortDescriptionInCompareProducts_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.IncludeShortDescriptionInCompareProducts, siteScope);
                model.IncludeFullDescriptionInCompareProducts_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.IncludeFullDescriptionInCompareProducts, siteScope);
                model.IgnoreDiscounts_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.IgnoreDiscounts, siteScope);
                model.IgnoreFeaturedProducts_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.IgnoreFeaturedProducts, siteScope);
                model.ManufacturersBlockItemsToDisplay_OverrideForSite = _settingService.SettingExists(catalogSettings, x => x.ManufacturersBlockItemsToDisplay, siteScope);
            }
            return View(model);
        }
        [HttpPost]
        public ActionResult Catalog(CatalogSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var catalogSettings = _settingService.LoadSetting<CatalogSettings>(siteScope);
            catalogSettings = model.ToEntity(catalogSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            if (model.ShowProductSku_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ShowProductSku, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ShowProductSku, siteScope);
            
            if (model.ShowManufacturerPartNumber_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ShowManufacturerPartNumber, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ShowManufacturerPartNumber, siteScope);
            
            if (model.ShowGtin_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ShowGtin, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ShowGtin, siteScope);
            
            if (model.AllowProductSorting_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.AllowProductSorting, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.AllowProductSorting, siteScope);
            
            if (model.AllowProductViewModeChanging_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.AllowProductViewModeChanging, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.AllowProductViewModeChanging, siteScope);
            
            if (model.ShowProductsFromSubcategories_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ShowProductsFromSubcategories, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ShowProductsFromSubcategories, siteScope);
            
            if (model.ShowCategoryProductNumber_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ShowCategoryProductNumber, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ShowCategoryProductNumber, siteScope);
            
            if (model.ShowCategoryProductNumberIncludingSubcategories_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ShowCategoryProductNumberIncludingSubcategories, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ShowCategoryProductNumberIncludingSubcategories, siteScope);
            
            if (model.CategoryBreadcrumbEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.CategoryBreadcrumbEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.CategoryBreadcrumbEnabled, siteScope);
            
            if (model.ShowShareButton_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ShowShareButton, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ShowShareButton, siteScope);
            
            if (model.ProductReviewsMustBeApproved_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ProductReviewsMustBeApproved, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ProductReviewsMustBeApproved, siteScope);
            
            if (model.AllowAnonymousUsersToReviewProduct_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.AllowAnonymousUsersToReviewProduct, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.AllowAnonymousUsersToReviewProduct, siteScope);
            
            if (model.NotifySiteOwnerAboutNewProductReviews_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.NotifySiteOwnerAboutNewProductReviews, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.NotifySiteOwnerAboutNewProductReviews, siteScope);
            
            if (model.EmailAFriendEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.EmailAFriendEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.EmailAFriendEnabled, siteScope);
            
            if (model.AllowAnonymousUsersToEmailAFriend_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.AllowAnonymousUsersToEmailAFriend, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.AllowAnonymousUsersToEmailAFriend, siteScope);
            
            if (model.RecentlyViewedProductsNumber_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.RecentlyViewedProductsNumber, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.RecentlyViewedProductsNumber, siteScope);
            
            if (model.RecentlyViewedProductsEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.RecentlyViewedProductsEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.RecentlyViewedProductsEnabled, siteScope);
            
            if (model.RecentlyAddedProductsNumber_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.RecentlyAddedProductsNumber, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.RecentlyAddedProductsNumber, siteScope);
            
            if (model.RecentlyAddedProductsEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.RecentlyAddedProductsEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.RecentlyAddedProductsEnabled, siteScope);
            
            if (model.CompareProductsEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.CompareProductsEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.CompareProductsEnabled, siteScope);
            
            if (model.ShowBestsellersOnHomepage_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ShowBestsellersOnHomepage, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ShowBestsellersOnHomepage, siteScope);
            
            if (model.NumberOfBestsellersOnHomepage_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.NumberOfBestsellersOnHomepage, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.NumberOfBestsellersOnHomepage, siteScope);
            
            if (model.SearchPageProductsPerPage_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.SearchPageProductsPerPage, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.SearchPageProductsPerPage, siteScope);
            
            if (model.ProductSearchAutoCompleteEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ProductSearchAutoCompleteEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ProductSearchAutoCompleteEnabled, siteScope);
            
            if (model.ProductSearchAutoCompleteNumberOfProducts_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ProductSearchAutoCompleteNumberOfProducts, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ProductSearchAutoCompleteNumberOfProducts, siteScope);
            
            if (model.ShowProductImagesInSearchAutoComplete_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ShowProductImagesInSearchAutoComplete, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ShowProductImagesInSearchAutoComplete, siteScope);
            
            if (model.ProductsAlsoPurchasedEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ProductsAlsoPurchasedEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ProductsAlsoPurchasedEnabled, siteScope);
            
            if (model.ProductsAlsoPurchasedNumber_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ProductsAlsoPurchasedNumber, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ProductsAlsoPurchasedNumber, siteScope);
            
            if (model.EnableDynamicPriceUpdate_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.EnableDynamicPriceUpdate, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.EnableDynamicPriceUpdate, siteScope);
            
            if (model.NumberOfProductTags_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.NumberOfProductTags, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.NumberOfProductTags, siteScope);
            
            if (model.ProductsByTagPageSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ProductsByTagPageSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ProductsByTagPageSize, siteScope);
            
            if (model.ProductsByTagAllowCustomersToSelectPageSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ProductsByTagAllowCustomersToSelectPageSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ProductsByTagAllowCustomersToSelectPageSize, siteScope);
            
            if (model.ProductsByTagPageSizeOptions_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ProductsByTagPageSizeOptions, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ProductsByTagPageSizeOptions, siteScope);
            
            if (model.IncludeShortDescriptionInCompareProducts_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.IncludeShortDescriptionInCompareProducts, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.IncludeShortDescriptionInCompareProducts, siteScope);
            
            if (model.IncludeFullDescriptionInCompareProducts_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.IncludeFullDescriptionInCompareProducts, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.IncludeFullDescriptionInCompareProducts, siteScope);
            
            if (model.IgnoreDiscounts_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.IgnoreDiscounts, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.IgnoreDiscounts, siteScope);
            
            if (model.IgnoreFeaturedProducts_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.IgnoreFeaturedProducts, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.IgnoreFeaturedProducts, siteScope);
            
            if (model.ManufacturersBlockItemsToDisplay_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(catalogSettings, x => x.ManufacturersBlockItemsToDisplay, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(catalogSettings, x => x.ManufacturersBlockItemsToDisplay, siteScope);

            //now clear settings cache
            _settingService.ClearCache();

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("Catalog");
        }



        public ActionResult RewardPoints()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var rewardPointsSettings = _settingService.LoadSetting<RewardPointsSettings>(siteScope);
            var model = rewardPointsSettings.ToModel();
            model.ActiveSiteScopeConfiguration = siteScope;
            if (siteScope > 0)
            {
                model.Enabled_OverrideForSite = _settingService.SettingExists(rewardPointsSettings, x => x.Enabled, siteScope);
                model.ExchangeRate_OverrideForSite = _settingService.SettingExists(rewardPointsSettings, x => x.ExchangeRate, siteScope);
                model.MinimumRewardPointsToUse_OverrideForSite = _settingService.SettingExists(rewardPointsSettings, x => x.MinimumRewardPointsToUse, siteScope);
                model.PointsForRegistration_OverrideForSite = _settingService.SettingExists(rewardPointsSettings, x => x.PointsForRegistration, siteScope);
                model.PointsForPurchases_OverrideForSite = _settingService.SettingExists(rewardPointsSettings, x => x.PointsForPurchases_Amount, siteScope) ||
                    _settingService.SettingExists(rewardPointsSettings, x => x.PointsForPurchases_Points, siteScope);
                model.PointsForPurchases_Awarded_OverrideForSite = _settingService.SettingExists(rewardPointsSettings, x => x.PointsForPurchases_Awarded, siteScope);
                model.PointsForPurchases_Canceled_OverrideForSite = _settingService.SettingExists(rewardPointsSettings, x => x.PointsForPurchases_Canceled, siteScope);
            }
            var currencySettings = _settingService.LoadSetting<CurrencySettings>(siteScope); 
            model.PrimarySiteCurrencyCode = _currencyService.GetCurrencyById(currencySettings.PrimarySiteCurrencyId).CurrencyCode;

            return View(model);
        }
        [HttpPost]
        public ActionResult RewardPoints(RewardPointsSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            if (ModelState.IsValid)
            {
                //load settings for a chosen site scope
                var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
                var rewardPointsSettings = _settingService.LoadSetting<RewardPointsSettings>(siteScope);
                rewardPointsSettings = model.ToEntity(rewardPointsSettings);

                /* We do not clear cache after each setting update.
                 * This behavior can increase performance because cached settings will not be cleared 
                 * and loaded from database after each update */
                if (model.Enabled_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(rewardPointsSettings, x => x.Enabled, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(rewardPointsSettings, x => x.Enabled, siteScope);
                
                if (model.ExchangeRate_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(rewardPointsSettings, x => x.ExchangeRate, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(rewardPointsSettings, x => x.ExchangeRate, siteScope);
                
                if (model.MinimumRewardPointsToUse_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(rewardPointsSettings, x => x.MinimumRewardPointsToUse, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(rewardPointsSettings, x => x.MinimumRewardPointsToUse, siteScope);
                
                if (model.PointsForRegistration_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(rewardPointsSettings, x => x.PointsForRegistration, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(rewardPointsSettings, x => x.PointsForRegistration, siteScope);
                
                if (model.PointsForPurchases_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(rewardPointsSettings, x => x.PointsForPurchases_Amount, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(rewardPointsSettings, x => x.PointsForPurchases_Amount, siteScope);

                if (model.PointsForPurchases_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(rewardPointsSettings, x => x.PointsForPurchases_Points, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(rewardPointsSettings, x => x.PointsForPurchases_Points, siteScope);
                
                if (model.PointsForPurchases_Awarded_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(rewardPointsSettings, x => x.PointsForPurchases_Awarded, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(rewardPointsSettings, x => x.PointsForPurchases_Awarded, siteScope);
                
                if (model.PointsForPurchases_Canceled_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(rewardPointsSettings, x => x.PointsForPurchases_Canceled, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(rewardPointsSettings, x => x.PointsForPurchases_Canceled, siteScope);

                //now clear settings cache
                _settingService.ClearCache();

                //activity log
                _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            }
            else
            {
                //If we got this far, something failed, redisplay form
                foreach (var modelState in ModelState.Values)
                    foreach (var error in modelState.Errors)
                        ErrorNotification(error.ErrorMessage);
            }
            return RedirectToAction("RewardPoints");
        }




        public ActionResult Order()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();



            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var orderSettings = _settingService.LoadSetting<OrderSettings>(siteScope);
            var model = orderSettings.ToModel();
            model.ActiveSiteScopeConfiguration = siteScope;
            if (siteScope > 0)
            {
                model.IsReOrderAllowed_OverrideForSite = _settingService.SettingExists(orderSettings, x => x.IsReOrderAllowed, siteScope);
                model.MinOrderSubtotalAmount_OverrideForSite = _settingService.SettingExists(orderSettings, x => x.MinOrderSubtotalAmount, siteScope);
                model.MinOrderTotalAmount_OverrideForSite = _settingService.SettingExists(orderSettings, x => x.MinOrderTotalAmount, siteScope);
                model.AnonymousCheckoutAllowed_OverrideForSite = _settingService.SettingExists(orderSettings, x => x.AnonymousCheckoutAllowed, siteScope);
                model.TermsOfServiceEnabled_OverrideForSite = _settingService.SettingExists(orderSettings, x => x.TermsOfServiceEnabled, siteScope);
                model.OnePageCheckoutEnabled_OverrideForSite = _settingService.SettingExists(orderSettings, x => x.OnePageCheckoutEnabled, siteScope);
                model.ReturnRequestsEnabled_OverrideForSite = _settingService.SettingExists(orderSettings, x => x.ReturnRequestsEnabled, siteScope);
                model.NumberOfDaysReturnRequestAvailable_OverrideForSite = _settingService.SettingExists(orderSettings, x => x.NumberOfDaysReturnRequestAvailable, siteScope);
            }

            var currencySettings = _settingService.LoadSetting<CurrencySettings>(siteScope);
            model.PrimarySiteCurrencyCode = _currencyService.GetCurrencyById(currencySettings.PrimarySiteCurrencyId).CurrencyCode;

            //gift card activation/deactivation
            model.GiftCards_Activated_OrderStatuses = OrderStatus.Pending.ToSelectList(false).ToList();
            model.GiftCards_Activated_OrderStatuses.Insert(0, new SelectListItem() { Text = "---", Value = "0" });
            model.GiftCards_Deactivated_OrderStatuses = OrderStatus.Pending.ToSelectList(false).ToList();
            model.GiftCards_Deactivated_OrderStatuses.Insert(0, new SelectListItem() { Text = "---", Value = "0" });


            //parse return request actions
            for (int i = 0; i < orderSettings.ReturnRequestActions.Count; i++)
            {
                model.ReturnRequestActionsParsed += orderSettings.ReturnRequestActions[i];
                if (i != orderSettings.ReturnRequestActions.Count - 1)
                    model.ReturnRequestActionsParsed += ",";
            }
            //parse return request reasons
            for (int i = 0; i < orderSettings.ReturnRequestReasons.Count; i++)
            {
                model.ReturnRequestReasonsParsed += orderSettings.ReturnRequestReasons[i];
                if (i != orderSettings.ReturnRequestReasons.Count - 1)
                    model.ReturnRequestReasonsParsed += ",";
            }

            //order ident
            model.OrderIdent = _maintenanceService.GetTableIdent<Order>();

            return View(model);
        }
        [HttpPost]
        public ActionResult Order(OrderSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            if (ModelState.IsValid)
            {
                //load settings for a chosen site scope
                var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
                var orderSettings = _settingService.LoadSetting<OrderSettings>(siteScope);
                orderSettings = model.ToEntity(orderSettings);

                /* We do not clear cache after each setting update.
                 * This behavior can increase performance because cached settings will not be cleared 
                 * and loaded from database after each update */
                if (model.IsReOrderAllowed_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(orderSettings, x => x.IsReOrderAllowed, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(orderSettings, x => x.IsReOrderAllowed, siteScope);
                
                if (model.MinOrderSubtotalAmount_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(orderSettings, x => x.MinOrderSubtotalAmount, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(orderSettings, x => x.MinOrderSubtotalAmount, siteScope);
                
                if (model.MinOrderTotalAmount_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(orderSettings, x => x.MinOrderTotalAmount, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(orderSettings, x => x.MinOrderTotalAmount, siteScope);
                
                if (model.AnonymousCheckoutAllowed_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(orderSettings, x => x.AnonymousCheckoutAllowed, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(orderSettings, x => x.AnonymousCheckoutAllowed, siteScope);
                
                if (model.TermsOfServiceEnabled_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(orderSettings, x => x.TermsOfServiceEnabled, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(orderSettings, x => x.TermsOfServiceEnabled, siteScope);
                
                if (model.OnePageCheckoutEnabled_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(orderSettings, x => x.OnePageCheckoutEnabled, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(orderSettings, x => x.OnePageCheckoutEnabled, siteScope);
                
                if (model.ReturnRequestsEnabled_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(orderSettings, x => x.ReturnRequestsEnabled, siteScope, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(orderSettings, x => x.ReturnRequestsEnabled, siteScope);

                //parse return request actions
                orderSettings.ReturnRequestActions.Clear();
                foreach (var returnAction in model.ReturnRequestActionsParsed.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    orderSettings.ReturnRequestActions.Add(returnAction);
                _settingService.SaveSetting(orderSettings, x => x.ReturnRequestActions, siteScope, false);
                //parse return request reasons
                orderSettings.ReturnRequestReasons.Clear();
                foreach (var returnReason in model.ReturnRequestReasonsParsed.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    orderSettings.ReturnRequestReasons.Add(returnReason);
                _settingService.SaveSetting(orderSettings, x => x.ReturnRequestReasons, siteScope, false);

                if (model.NumberOfDaysReturnRequestAvailable_OverrideForSite || siteScope == 0)
                    _settingService.SaveSetting(orderSettings, x => x.NumberOfDaysReturnRequestAvailable, 0, false);
                else if (siteScope > 0)
                    _settingService.DeleteSetting(orderSettings, x => x.NumberOfDaysReturnRequestAvailable, 0);

                _settingService.SaveSetting(orderSettings, x => x.GiftCards_Activated_OrderStatusId, 0, false);
                _settingService.SaveSetting(orderSettings, x => x.GiftCards_Deactivated_OrderStatusId, 0, false);
                
                //now clear settings cache
                _settingService.ClearCache();
                
                //order ident
                if (model.OrderIdent.HasValue)
                {
                    try
                    {
                        _maintenanceService.SetTableIdent<Order>(model.OrderIdent.Value);
                    }
                    catch (Exception exc)
                    {
                        ErrorNotification(exc.Message);
                    }
                }

                //activity log
                _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            }
            else
            {
                //If we got this far, something failed, redisplay form
                foreach (var modelState in ModelState.Values)
                    foreach (var error in modelState.Errors)
                        ErrorNotification(error.ErrorMessage);
            }
            return RedirectToAction("Order");
        }




        public ActionResult ShoppingCart()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var shoppingCartSettings = _settingService.LoadSetting<ShoppingCartSettings>(siteScope);
            var model = shoppingCartSettings.ToModel();
            model.ActiveSiteScopeConfiguration = siteScope;
            if (siteScope > 0)
            {
                model.DisplayCartAfterAddingProduct_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.DisplayCartAfterAddingProduct, siteScope);
                model.DisplayWishlistAfterAddingProduct_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.DisplayWishlistAfterAddingProduct, siteScope);
                model.MaximumShoppingCartItems_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.MaximumShoppingCartItems, siteScope);
                model.MaximumWishlistItems_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.MaximumWishlistItems, siteScope);
                model.AllowOutOfStockItemsToBeAddedToWishlist_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.AllowOutOfStockItemsToBeAddedToWishlist, siteScope);
                model.MoveItemsFromWishlistToCart_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.MoveItemsFromWishlistToCart, siteScope);
                model.ShowProductImagesOnShoppingCart_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.ShowProductImagesOnShoppingCart, siteScope);
                model.ShowProductImagesOnWishList_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.ShowProductImagesOnWishList, siteScope);
                model.ShowDiscountBox_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.ShowDiscountBox, siteScope);
                model.ShowGiftCardBox_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.ShowGiftCardBox, siteScope);
                model.CrossSellsNumber_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.CrossSellsNumber, siteScope);
                model.EmailWishlistEnabled_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.EmailWishlistEnabled, siteScope);
                model.AllowAnonymousUsersToEmailWishlist_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.AllowAnonymousUsersToEmailWishlist, siteScope);
                model.MiniShoppingCartEnabled_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.MiniShoppingCartEnabled, siteScope);
                model.ShowProductImagesInMiniShoppingCart_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.ShowProductImagesInMiniShoppingCart, siteScope);
                model.MiniShoppingCartProductNumber_OverrideForSite = _settingService.SettingExists(shoppingCartSettings, x => x.MiniShoppingCartProductNumber, siteScope);
            }
            return View(model);
        }
        [HttpPost]
        public ActionResult ShoppingCart(ShoppingCartSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var shoppingCartSettings = _settingService.LoadSetting<ShoppingCartSettings>(siteScope);
            shoppingCartSettings = model.ToEntity(shoppingCartSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            if (model.DisplayCartAfterAddingProduct_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.DisplayCartAfterAddingProduct, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.DisplayCartAfterAddingProduct, siteScope);
            
            if (model.DisplayWishlistAfterAddingProduct_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.DisplayWishlistAfterAddingProduct, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.DisplayWishlistAfterAddingProduct, siteScope);
            
            if (model.MaximumShoppingCartItems_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.MaximumShoppingCartItems, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.MaximumShoppingCartItems, siteScope);
            
            if (model.MaximumWishlistItems_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.MaximumWishlistItems, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.MaximumWishlistItems, siteScope);
            
            if (model.AllowOutOfStockItemsToBeAddedToWishlist_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.AllowOutOfStockItemsToBeAddedToWishlist, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.AllowOutOfStockItemsToBeAddedToWishlist, siteScope);
            
            if (model.MoveItemsFromWishlistToCart_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.MoveItemsFromWishlistToCart, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.MoveItemsFromWishlistToCart, siteScope);
            
            if (model.ShowProductImagesOnShoppingCart_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.ShowProductImagesOnShoppingCart, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.ShowProductImagesOnShoppingCart, siteScope);
            
            if (model.ShowProductImagesOnWishList_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.ShowProductImagesOnWishList, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.ShowProductImagesOnWishList, siteScope);
            
            if (model.ShowDiscountBox_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.ShowDiscountBox, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.ShowDiscountBox, siteScope);
            
            if (model.ShowGiftCardBox_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.ShowGiftCardBox, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.ShowGiftCardBox, siteScope);
            
            if (model.CrossSellsNumber_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.CrossSellsNumber, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.CrossSellsNumber, siteScope);
            
            if (model.EmailWishlistEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.EmailWishlistEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.EmailWishlistEnabled, siteScope);
            
            if (model.AllowAnonymousUsersToEmailWishlist_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.AllowAnonymousUsersToEmailWishlist, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.AllowAnonymousUsersToEmailWishlist, siteScope);
            
            if (model.MiniShoppingCartEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.MiniShoppingCartEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.MiniShoppingCartEnabled, siteScope);
            
            if (model.ShowProductImagesInMiniShoppingCart_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.ShowProductImagesInMiniShoppingCart, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.ShowProductImagesInMiniShoppingCart, siteScope);

            if (model.MiniShoppingCartProductNumber_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(shoppingCartSettings, x => x.MiniShoppingCartProductNumber, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(shoppingCartSettings, x => x.MiniShoppingCartProductNumber, siteScope);

            //now clear settings cache
            _settingService.ClearCache();
            

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("ShoppingCart");
        }




        public ActionResult Media()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var mediaSettings = _settingService.LoadSetting<MediaSettings>(siteScope);
            var model = mediaSettings.ToModel();
            model.ActiveSiteScopeConfiguration = siteScope;
            if (siteScope > 0)
            {
                model.AvatarPictureSize_OverrideForSite = _settingService.SettingExists(mediaSettings, x => x.AvatarPictureSize, siteScope);
                model.ProductThumbPictureSize_OverrideForSite = _settingService.SettingExists(mediaSettings, x => x.ProductThumbPictureSize, siteScope);
                model.ProductDetailsPictureSize_OverrideForSite = _settingService.SettingExists(mediaSettings, x => x.ProductDetailsPictureSize, siteScope);
                model.ProductThumbPictureSizeOnProductDetailsPage_OverrideForSite = _settingService.SettingExists(mediaSettings, x => x.ProductThumbPictureSizeOnProductDetailsPage, siteScope);
                model.ProductVariantPictureSize_OverrideForSite = _settingService.SettingExists(mediaSettings, x => x.ProductVariantPictureSize, siteScope);
                model.CategoryThumbPictureSize_OverrideForSite = _settingService.SettingExists(mediaSettings, x => x.CategoryThumbPictureSize, siteScope);
                model.ManufacturerThumbPictureSize_OverrideForSite = _settingService.SettingExists(mediaSettings, x => x.ManufacturerThumbPictureSize, siteScope);
                model.CartThumbPictureSize_OverrideForSite = _settingService.SettingExists(mediaSettings, x => x.CartThumbPictureSize, siteScope);
                model.MiniCartThumbPictureSize_OverrideForSite = _settingService.SettingExists(mediaSettings, x => x.MiniCartThumbPictureSize, siteScope);
                model.MaximumImageSize_OverrideForSite = _settingService.SettingExists(mediaSettings, x => x.MaximumImageSize, siteScope);
            }
            model.PicturesSitedIntoDatabase = _pictureService.SiteInDb;
            return View(model);
        }
        [HttpPost]
        [FormValueRequired("save")]
        public ActionResult Media(MediaSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var mediaSettings = _settingService.LoadSetting<MediaSettings>(siteScope);
            mediaSettings = model.ToEntity(mediaSettings);

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            if (model.AvatarPictureSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(mediaSettings, x => x.AvatarPictureSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(mediaSettings, x => x.AvatarPictureSize, siteScope);
            
            if (model.ProductThumbPictureSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(mediaSettings, x => x.ProductThumbPictureSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(mediaSettings, x => x.ProductThumbPictureSize, siteScope);
            
            if (model.ProductDetailsPictureSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(mediaSettings, x => x.ProductDetailsPictureSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(mediaSettings, x => x.ProductDetailsPictureSize, siteScope);
            
            if (model.ProductThumbPictureSizeOnProductDetailsPage_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(mediaSettings, x => x.ProductThumbPictureSizeOnProductDetailsPage, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(mediaSettings, x => x.ProductThumbPictureSizeOnProductDetailsPage, siteScope);
            
            if (model.ProductVariantPictureSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(mediaSettings, x => x.ProductVariantPictureSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(mediaSettings, x => x.ProductVariantPictureSize, siteScope);
            
            if (model.CategoryThumbPictureSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(mediaSettings, x => x.CategoryThumbPictureSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(mediaSettings, x => x.CategoryThumbPictureSize, siteScope);
            
            if (model.ManufacturerThumbPictureSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(mediaSettings, x => x.ManufacturerThumbPictureSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(mediaSettings, x => x.ManufacturerThumbPictureSize, siteScope);
            
            if (model.CartThumbPictureSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(mediaSettings, x => x.CartThumbPictureSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(mediaSettings, x => x.CartThumbPictureSize, siteScope);
            
            if (model.MiniCartThumbPictureSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(mediaSettings, x => x.MiniCartThumbPictureSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(mediaSettings, x => x.MiniCartThumbPictureSize, siteScope);

            if (model.MaximumImageSize_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(mediaSettings, x => x.MaximumImageSize, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(mediaSettings, x => x.MaximumImageSize, siteScope);
                
            //now clear settings cache
            _settingService.ClearCache();
            
            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("Media");
        }
        [HttpPost, ActionName("Media")]
        [FormValueRequired("change-picture-storage")]
        public ActionResult ChangePictureStorage()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            _pictureService.SiteInDb = !_pictureService.SiteInDb;

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("Media");
        }



        public ActionResult CustomerUser()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var customerSettings = _settingService.LoadSetting<CustomerSettings>(siteScope);
            var addressSettings = _settingService.LoadSetting<AddressSettings>(siteScope);
            var dateTimeSettings = _settingService.LoadSetting<DateTimeSettings>(siteScope);
            var externalAuthenticationSettings = _settingService.LoadSetting<ExternalAuthenticationSettings>(siteScope);

            //merge settings
            var model = new CustomerUserSettingsModel();
            model.CustomerSettings = customerSettings.ToModel();
            model.AddressSettings = addressSettings.ToModel();

            model.DateTimeSettings.AllowCustomersToSetTimeZone = dateTimeSettings.AllowCustomersToSetTimeZone;
            model.DateTimeSettings.DefaultSiteTimeZoneId = _dateTimeHelper.DefaultSiteTimeZone.Id;
            foreach (TimeZoneInfo timeZone in _dateTimeHelper.GetSystemTimeZones())
            {
                model.DateTimeSettings.AvailableTimeZones.Add(new SelectListItem()
                    {
                        Text = timeZone.DisplayName,
                        Value = timeZone.Id,
                        Selected = timeZone.Id.Equals(_dateTimeHelper.DefaultSiteTimeZone.Id, StringComparison.InvariantCultureIgnoreCase)
                    });
            }

            model.ExternalAuthenticationSettings.AutoRegisterEnabled = externalAuthenticationSettings.AutoRegisterEnabled;

            return View(model);
        }
        [HttpPost]
        public ActionResult CustomerUser(CustomerUserSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var customerSettings = _settingService.LoadSetting<CustomerSettings>(siteScope);
            var addressSettings = _settingService.LoadSetting<AddressSettings>(siteScope);
            var dateTimeSettings = _settingService.LoadSetting<DateTimeSettings>(siteScope);
            var externalAuthenticationSettings = _settingService.LoadSetting<ExternalAuthenticationSettings>(siteScope);

            customerSettings = model.CustomerSettings.ToEntity(customerSettings);
            _settingService.SaveSetting(customerSettings);

            addressSettings = model.AddressSettings.ToEntity(addressSettings);
            _settingService.SaveSetting(addressSettings);

            dateTimeSettings.DefaultSiteTimeZoneId = model.DateTimeSettings.DefaultSiteTimeZoneId;
            dateTimeSettings.AllowCustomersToSetTimeZone = model.DateTimeSettings.AllowCustomersToSetTimeZone;
            _settingService.SaveSetting(dateTimeSettings);

            externalAuthenticationSettings.AutoRegisterEnabled = model.ExternalAuthenticationSettings.AutoRegisterEnabled;
            _settingService.SaveSetting(externalAuthenticationSettings);

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("CustomerUser");
        }






        public ActionResult GeneralCommon(string selectedTab)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            var model = new GeneralCommonSettingsModel();
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            model.ActiveSiteScopeConfiguration = siteScope;
            //site information
            var siteInformationSettings = _settingService.LoadSetting<SiteInformationSettings>(siteScope);
            model.SiteInformationSettings.SiteClosed = siteInformationSettings.SiteClosed;
            model.SiteInformationSettings.SiteClosedAllowForAdmins = siteInformationSettings.SiteClosedAllowForAdmins;
            //desktop themes
            model.SiteInformationSettings.DefaultSiteThemeForDesktops = siteInformationSettings.DefaultSiteThemeForDesktops;
            model.SiteInformationSettings.AvailableSiteThemesForDesktops = _themeProvider
                .GetThemeConfigurations()
                .Where(x => !x.MobileTheme)
                .Select(x =>
                {
                    return new SelectListItem()
                    {
                        Text = x.ThemeTitle,
                        Value = x.ThemeName,
                        Selected = x.ThemeName.Equals(siteInformationSettings.DefaultSiteThemeForDesktops, StringComparison.InvariantCultureIgnoreCase)
                    };
                })
                .ToList();
            model.SiteInformationSettings.AllowCustomerToSelectTheme = siteInformationSettings.AllowCustomerToSelectTheme;
            model.SiteInformationSettings.MobileDevicesSupported = siteInformationSettings.MobileDevicesSupported;
            //mobile device themes
            model.SiteInformationSettings.DefaultSiteThemeForMobileDevices = siteInformationSettings.DefaultSiteThemeForMobileDevices;
            model.SiteInformationSettings.AvailableSiteThemesForMobileDevices = _themeProvider
                .GetThemeConfigurations()
                .Where(x => x.MobileTheme)
                .Select(x =>
                {
                    return new SelectListItem()
                    {
                        Text = x.ThemeTitle,
                        Value = x.ThemeName,
                        Selected = x.ThemeName.Equals(siteInformationSettings.DefaultSiteThemeForMobileDevices, StringComparison.InvariantCultureIgnoreCase)
                    };
                })
                .ToList();


            //override settings
            if (siteScope > 0)
            {
                model.SiteInformationSettings.MobileDevicesSupported_OverrideForSite = _settingService.SettingExists(siteInformationSettings, x => x.MobileDevicesSupported, siteScope);
                model.SiteInformationSettings.SiteClosed_OverrideForSite = _settingService.SettingExists(siteInformationSettings, x => x.SiteClosed, siteScope);
                model.SiteInformationSettings.SiteClosedAllowForAdmins_OverrideForSite = _settingService.SettingExists(siteInformationSettings, x => x.SiteClosedAllowForAdmins, siteScope);
                model.SiteInformationSettings.DefaultSiteThemeForDesktops_OverrideForSite = _settingService.SettingExists(siteInformationSettings, x => x.DefaultSiteThemeForDesktops, siteScope);
                model.SiteInformationSettings.DefaultSiteThemeForMobileDevices_OverrideForSite = _settingService.SettingExists(siteInformationSettings, x => x.DefaultSiteThemeForMobileDevices, siteScope);
                model.SiteInformationSettings.AllowCustomerToSelectTheme_OverrideForSite = _settingService.SettingExists(siteInformationSettings, x => x.AllowCustomerToSelectTheme, siteScope);
            }

            //seo settings
            var seoSettings = _settingService.LoadSetting<SeoSettings>(siteScope);
            model.SeoSettings.PageTitleSeparator = seoSettings.PageTitleSeparator;
            model.SeoSettings.PageTitleSeoAdjustment = (int)seoSettings.PageTitleSeoAdjustment;
            model.SeoSettings.PageTitleSeoAdjustmentValues = seoSettings.PageTitleSeoAdjustment.ToSelectList();
            model.SeoSettings.DefaultTitle = seoSettings.DefaultTitle;
            model.SeoSettings.DefaultMetaKeywords = seoSettings.DefaultMetaKeywords;
            model.SeoSettings.DefaultMetaDescription = seoSettings.DefaultMetaDescription;
            model.SeoSettings.ConvertNonWesternChars = seoSettings.ConvertNonWesternChars;
            model.SeoSettings.CanonicalUrlsEnabled = seoSettings.CanonicalUrlsEnabled;
            //override settings
            if (siteScope > 0)
            {
                model.SeoSettings.PageTitleSeparator_OverrideForSite = _settingService.SettingExists(seoSettings, x => x.PageTitleSeparator, siteScope);
                model.SeoSettings.PageTitleSeoAdjustment_OverrideForSite = _settingService.SettingExists(seoSettings, x => x.PageTitleSeoAdjustment, siteScope);
                model.SeoSettings.DefaultTitle_OverrideForSite = _settingService.SettingExists(seoSettings, x => x.DefaultTitle, siteScope);
                model.SeoSettings.DefaultMetaKeywords_OverrideForSite = _settingService.SettingExists(seoSettings, x => x.DefaultMetaKeywords, siteScope);
                model.SeoSettings.DefaultMetaDescription_OverrideForSite = _settingService.SettingExists(seoSettings, x => x.DefaultMetaDescription, siteScope);
                model.SeoSettings.ConvertNonWesternChars_OverrideForSite = _settingService.SettingExists(seoSettings, x => x.ConvertNonWesternChars, siteScope);
                model.SeoSettings.CanonicalUrlsEnabled_OverrideForSite = _settingService.SettingExists(seoSettings, x => x.CanonicalUrlsEnabled, siteScope);
            }
            
            //security settings
            var securitySettings = _settingService.LoadSetting<SecuritySettings>(siteScope);
            var captchaSettings = _settingService.LoadSetting<CaptchaSettings>(siteScope);
            model.SecuritySettings.EncryptionKey = securitySettings.EncryptionKey;
            if (securitySettings.AdminAreaAllowedIpAddresses != null)
                for (int i = 0; i < securitySettings.AdminAreaAllowedIpAddresses.Count; i++)
                {
                    model.SecuritySettings.AdminAreaAllowedIpAddresses += securitySettings.AdminAreaAllowedIpAddresses[i];
                    if (i != securitySettings.AdminAreaAllowedIpAddresses.Count - 1)
                        model.SecuritySettings.AdminAreaAllowedIpAddresses += ",";
                }
            model.SecuritySettings.HideAdminMenuItemsBasedOnPermissions = securitySettings.HideAdminMenuItemsBasedOnPermissions;
            model.SecuritySettings.CaptchaEnabled = captchaSettings.Enabled;
            model.SecuritySettings.CaptchaShowOnLoginPage = captchaSettings.ShowOnLoginPage;
            model.SecuritySettings.CaptchaShowOnRegistrationPage = captchaSettings.ShowOnRegistrationPage;
            model.SecuritySettings.CaptchaShowOnContactUsPage = captchaSettings.ShowOnContactUsPage;
            model.SecuritySettings.CaptchaShowOnEmailWishlistToFriendPage = captchaSettings.ShowOnEmailWishlistToFriendPage;
            model.SecuritySettings.CaptchaShowOnEmailProductToFriendPage = captchaSettings.ShowOnEmailProductToFriendPage;
            model.SecuritySettings.CaptchaShowOnBlogCommentPage = captchaSettings.ShowOnBlogCommentPage;
            model.SecuritySettings.CaptchaShowOnNewsCommentPage = captchaSettings.ShowOnNewsCommentPage;
            model.SecuritySettings.CaptchaShowOnProductReviewPage = captchaSettings.ShowOnProductReviewPage;
            model.SecuritySettings.ReCaptchaPublicKey = captchaSettings.ReCaptchaPublicKey;
            model.SecuritySettings.ReCaptchaPrivateKey = captchaSettings.ReCaptchaPrivateKey;

            //PDF settings
            var pdfSettings = _settingService.LoadSetting<PdfSettings>(siteScope);
            model.PdfSettings.Enabled = pdfSettings.Enabled;
            model.PdfSettings.LetterPageSizeEnabled = pdfSettings.LetterPageSizeEnabled;
            model.PdfSettings.LogoPictureId = pdfSettings.LogoPictureId;
            //override settings
            if (siteScope > 0)
            {
                model.PdfSettings.Enabled_OverrideForSite = _settingService.SettingExists(pdfSettings, x => x.Enabled, siteScope);
                model.PdfSettings.LetterPageSizeEnabled_OverrideForSite = _settingService.SettingExists(pdfSettings, x => x.LetterPageSizeEnabled, siteScope);
                model.PdfSettings.LogoPictureId_OverrideForSite = _settingService.SettingExists(pdfSettings, x => x.LogoPictureId, siteScope);
            }

            //localization
            var localizationSettings = _settingService.LoadSetting<LocalizationSettings>(siteScope);
            model.LocalizationSettings.UseImagesForLanguageSelection = localizationSettings.UseImagesForLanguageSelection;
            model.LocalizationSettings.SeoFriendlyUrlsForLanguagesEnabled = localizationSettings.SeoFriendlyUrlsForLanguagesEnabled;
            model.LocalizationSettings.LoadAllLocaleRecordsOnStartup = localizationSettings.LoadAllLocaleRecordsOnStartup;

            //full-text support
            var commonSettings = _settingService.LoadSetting<CommonSettings>(siteScope);
            model.FullTextSettings.Supported = _fulltextService.IsFullTextSupported();
            model.FullTextSettings.Enabled = commonSettings.UseFullTextSearch;
            model.FullTextSettings.SearchMode = (int)commonSettings.FullTextMode;
            model.FullTextSettings.SearchModeValues = commonSettings.FullTextMode.ToSelectList();
            ViewData["selectedTab"] = selectedTab;
            return View(model);
        }
        [HttpPost]
        [FormValueRequired("save")]
        public ActionResult GeneralCommon(GeneralCommonSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();


            //load settings for a chosen site scope
            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);

            //site information settings
            var siteInformationSettings = _settingService.LoadSetting<SiteInformationSettings>(siteScope);
            siteInformationSettings.SiteClosed = model.SiteInformationSettings.SiteClosed;
            siteInformationSettings.SiteClosedAllowForAdmins = model.SiteInformationSettings.SiteClosedAllowForAdmins;
            siteInformationSettings.DefaultSiteThemeForDesktops = model.SiteInformationSettings.DefaultSiteThemeForDesktops;
            siteInformationSettings.AllowCustomerToSelectTheme = model.SiteInformationSettings.AllowCustomerToSelectTheme;
            //site whether MobileDevicesSupported setting has been changed (requires application restart)
            bool mobileDevicesSupportedChanged = siteInformationSettings.MobileDevicesSupported !=
                                                 model.SiteInformationSettings.MobileDevicesSupported;
            siteInformationSettings.MobileDevicesSupported = model.SiteInformationSettings.MobileDevicesSupported;
            siteInformationSettings.DefaultSiteThemeForMobileDevices = model.SiteInformationSettings.DefaultSiteThemeForMobileDevices;

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            if (model.SiteInformationSettings.MobileDevicesSupported_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(siteInformationSettings, x => x.MobileDevicesSupported, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(siteInformationSettings, x => x.MobileDevicesSupported, siteScope);

            if (model.SiteInformationSettings.SiteClosed_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(siteInformationSettings, x => x.SiteClosed, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(siteInformationSettings, x => x.SiteClosed, siteScope);

            if (model.SiteInformationSettings.SiteClosedAllowForAdmins_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(siteInformationSettings, x => x.SiteClosedAllowForAdmins, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(siteInformationSettings, x => x.SiteClosedAllowForAdmins, siteScope);

            if (model.SiteInformationSettings.DefaultSiteThemeForDesktops_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(siteInformationSettings, x => x.DefaultSiteThemeForDesktops, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(siteInformationSettings, x => x.DefaultSiteThemeForDesktops, siteScope);

            if (model.SiteInformationSettings.DefaultSiteThemeForMobileDevices_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(siteInformationSettings, x => x.DefaultSiteThemeForMobileDevices, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(siteInformationSettings, x => x.DefaultSiteThemeForMobileDevices, siteScope);

            if (model.SiteInformationSettings.AllowCustomerToSelectTheme_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(siteInformationSettings, x => x.AllowCustomerToSelectTheme, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(siteInformationSettings, x => x.AllowCustomerToSelectTheme, siteScope);

            //now clear settings cache
            _settingService.ClearCache();



            //seo settings
            var seoSettings = _settingService.LoadSetting<SeoSettings>(siteScope);
            seoSettings.PageTitleSeparator = model.SeoSettings.PageTitleSeparator;
            seoSettings.PageTitleSeoAdjustment = (PageTitleSeoAdjustment)model.SeoSettings.PageTitleSeoAdjustment;
            seoSettings.DefaultTitle = model.SeoSettings.DefaultTitle;
            seoSettings.DefaultMetaKeywords = model.SeoSettings.DefaultMetaKeywords;
            seoSettings.DefaultMetaDescription = model.SeoSettings.DefaultMetaDescription;
            seoSettings.ConvertNonWesternChars = model.SeoSettings.ConvertNonWesternChars;
            seoSettings.CanonicalUrlsEnabled = model.SeoSettings.CanonicalUrlsEnabled;

            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            if (model.SeoSettings.PageTitleSeparator_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(seoSettings, x => x.PageTitleSeparator, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(seoSettings, x => x.PageTitleSeparator, siteScope);
            
            if (model.SeoSettings.PageTitleSeoAdjustment_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(seoSettings, x => x.PageTitleSeoAdjustment, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(seoSettings, x => x.PageTitleSeoAdjustment, siteScope);
            
            if (model.SeoSettings.DefaultTitle_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(seoSettings, x => x.DefaultTitle, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(seoSettings, x => x.DefaultTitle, siteScope);
            
            if (model.SeoSettings.DefaultMetaKeywords_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(seoSettings, x => x.DefaultMetaKeywords, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(seoSettings, x => x.DefaultMetaKeywords, siteScope);
            
            if (model.SeoSettings.DefaultMetaDescription_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(seoSettings, x => x.DefaultMetaDescription, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(seoSettings, x => x.DefaultMetaDescription, siteScope);
            
            if (model.SeoSettings.ConvertNonWesternChars_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(seoSettings, x => x.ConvertNonWesternChars, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(seoSettings, x => x.ConvertNonWesternChars, siteScope);
            
            if (model.SeoSettings.CanonicalUrlsEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(seoSettings, x => x.CanonicalUrlsEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(seoSettings, x => x.CanonicalUrlsEnabled, siteScope);

            //now clear settings cache
            _settingService.ClearCache();



            //security settings
            var securitySettings = _settingService.LoadSetting<SecuritySettings>(siteScope);
            var captchaSettings = _settingService.LoadSetting<CaptchaSettings>(siteScope);
            if (securitySettings.AdminAreaAllowedIpAddresses == null)
                securitySettings.AdminAreaAllowedIpAddresses = new List<string>();
            securitySettings.AdminAreaAllowedIpAddresses.Clear();
            if (!String.IsNullOrEmpty(model.SecuritySettings.AdminAreaAllowedIpAddresses))
                foreach (string s in model.SecuritySettings.AdminAreaAllowedIpAddresses.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    if (!String.IsNullOrWhiteSpace(s))
                        securitySettings.AdminAreaAllowedIpAddresses.Add(s.Trim());
            securitySettings.HideAdminMenuItemsBasedOnPermissions = model.SecuritySettings.HideAdminMenuItemsBasedOnPermissions;
            _settingService.SaveSetting(securitySettings);
            captchaSettings.Enabled = model.SecuritySettings.CaptchaEnabled;
            captchaSettings.ShowOnLoginPage = model.SecuritySettings.CaptchaShowOnLoginPage;
            captchaSettings.ShowOnRegistrationPage = model.SecuritySettings.CaptchaShowOnRegistrationPage;
            captchaSettings.ShowOnContactUsPage = model.SecuritySettings.CaptchaShowOnContactUsPage;
            captchaSettings.ShowOnEmailWishlistToFriendPage = model.SecuritySettings.CaptchaShowOnEmailWishlistToFriendPage;
            captchaSettings.ShowOnEmailProductToFriendPage = model.SecuritySettings.CaptchaShowOnEmailProductToFriendPage;
            captchaSettings.ShowOnBlogCommentPage = model.SecuritySettings.CaptchaShowOnBlogCommentPage;
            captchaSettings.ShowOnNewsCommentPage = model.SecuritySettings.CaptchaShowOnNewsCommentPage;
            captchaSettings.ShowOnProductReviewPage = model.SecuritySettings.CaptchaShowOnProductReviewPage;
            captchaSettings.ReCaptchaPublicKey = model.SecuritySettings.ReCaptchaPublicKey;
            captchaSettings.ReCaptchaPrivateKey = model.SecuritySettings.ReCaptchaPrivateKey;
            _settingService.SaveSetting(captchaSettings);
            if (captchaSettings.Enabled &&
                (String.IsNullOrWhiteSpace(captchaSettings.ReCaptchaPublicKey) || String.IsNullOrWhiteSpace(captchaSettings.ReCaptchaPrivateKey)))
            {
                //captcha is enabled but the keys are not entered
                ErrorNotification("Captcha is enabled but the appropriate keys are not entered");
            }

            //PDF settings
            var pdfSettings = _settingService.LoadSetting<PdfSettings>(siteScope);
            pdfSettings.Enabled = model.PdfSettings.Enabled;
            pdfSettings.LetterPageSizeEnabled = model.PdfSettings.LetterPageSizeEnabled;
            pdfSettings.LogoPictureId = model.PdfSettings.LogoPictureId;
            /* We do not clear cache after each setting update.
             * This behavior can increase performance because cached settings will not be cleared 
             * and loaded from database after each update */
            if (model.PdfSettings.Enabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(pdfSettings, x => x.Enabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(pdfSettings, x => x.Enabled, siteScope);
            
            if (model.PdfSettings.LetterPageSizeEnabled_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(pdfSettings, x => x.LetterPageSizeEnabled, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(pdfSettings, x => x.LetterPageSizeEnabled, siteScope);

            if (model.PdfSettings.LogoPictureId_OverrideForSite || siteScope == 0)
                _settingService.SaveSetting(pdfSettings, x => x.LogoPictureId, siteScope, false);
            else if (siteScope > 0)
                _settingService.DeleteSetting(pdfSettings, x => x.LogoPictureId, siteScope);
            
            //now clear settings cache
            _settingService.ClearCache();




            //localization settings
            var localizationSettings = _settingService.LoadSetting<LocalizationSettings>(siteScope);
            localizationSettings.UseImagesForLanguageSelection = model.LocalizationSettings.UseImagesForLanguageSelection;
            if (localizationSettings.SeoFriendlyUrlsForLanguagesEnabled != model.LocalizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
            {
                localizationSettings.SeoFriendlyUrlsForLanguagesEnabled = model.LocalizationSettings.SeoFriendlyUrlsForLanguagesEnabled;
                //clear cached values of routes
                System.Web.Routing.RouteTable.Routes.ClearSeoFriendlyUrlsCachedValueForRoutes();
            }
            localizationSettings.LoadAllLocaleRecordsOnStartup = model.LocalizationSettings.LoadAllLocaleRecordsOnStartup;
            _settingService.SaveSetting(localizationSettings);

            //full-text
            var commonSettings = _settingService.LoadSetting<CommonSettings>(siteScope);
            commonSettings.FullTextMode = (FulltextSearchMode)model.FullTextSettings.SearchMode;
            _settingService.SaveSetting(commonSettings);

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            if (mobileDevicesSupportedChanged)
            {
                //MobileDevicesSupported setting has been changed
                //restart application
                _webHelper.RestartAppDomain();
            }

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.Updated"));
            return RedirectToAction("GeneralCommon");
        }
        [HttpPost, ActionName("GeneralCommon")]
        [FormValueRequired("changeencryptionkey")]
        public ActionResult ChangeEncryptionKey(GeneralCommonSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var securitySettings = _settingService.LoadSetting<SecuritySettings>(siteScope);

            try
            {
                if (model.SecuritySettings.EncryptionKey == null)
                    model.SecuritySettings.EncryptionKey = "";

                model.SecuritySettings.EncryptionKey = model.SecuritySettings.EncryptionKey.Trim();

                var newEncryptionPrivateKey = model.SecuritySettings.EncryptionKey;
                if (String.IsNullOrEmpty(newEncryptionPrivateKey) || newEncryptionPrivateKey.Length != 16)
                    throw new CmsException(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.EncryptionKey.TooShort"));

                string oldEncryptionPrivateKey = securitySettings.EncryptionKey;
                if (oldEncryptionPrivateKey == newEncryptionPrivateKey)
                    throw new CmsException(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.EncryptionKey.TheSame"));

                //update encrypted order info
                var orders = _orderService.SearchOrders(0, 0, null, null, null, null, null, null, null, 0, int.MaxValue);
                foreach (var order in orders)
                {
                    string decryptedCardType = _encryptionService.DecryptText(order.CardType, oldEncryptionPrivateKey);
                    string decryptedCardName = _encryptionService.DecryptText(order.CardName, oldEncryptionPrivateKey);
                    string decryptedCardNumber = _encryptionService.DecryptText(order.CardNumber, oldEncryptionPrivateKey);
                    string decryptedMaskedCreditCardNumber = _encryptionService.DecryptText(order.MaskedCreditCardNumber, oldEncryptionPrivateKey);
                    string decryptedCardCvv2 = _encryptionService.DecryptText(order.CardCvv2, oldEncryptionPrivateKey);
                    string decryptedCardExpirationMonth = _encryptionService.DecryptText(order.CardExpirationMonth, oldEncryptionPrivateKey);
                    string decryptedCardExpirationYear = _encryptionService.DecryptText(order.CardExpirationYear, oldEncryptionPrivateKey);

                    string encryptedCardType = _encryptionService.EncryptText(decryptedCardType, newEncryptionPrivateKey);
                    string encryptedCardName = _encryptionService.EncryptText(decryptedCardName, newEncryptionPrivateKey);
                    string encryptedCardNumber = _encryptionService.EncryptText(decryptedCardNumber, newEncryptionPrivateKey);
                    string encryptedMaskedCreditCardNumber = _encryptionService.EncryptText(decryptedMaskedCreditCardNumber, newEncryptionPrivateKey);
                    string encryptedCardCvv2 = _encryptionService.EncryptText(decryptedCardCvv2, newEncryptionPrivateKey);
                    string encryptedCardExpirationMonth = _encryptionService.EncryptText(decryptedCardExpirationMonth, newEncryptionPrivateKey);
                    string encryptedCardExpirationYear = _encryptionService.EncryptText(decryptedCardExpirationYear, newEncryptionPrivateKey);

                    order.CardType = encryptedCardType;
                    order.CardName = encryptedCardName;
                    order.CardNumber = encryptedCardNumber;
                    order.MaskedCreditCardNumber = encryptedMaskedCreditCardNumber;
                    order.CardCvv2 = encryptedCardCvv2;
                    order.CardExpirationMonth = encryptedCardExpirationMonth;
                    order.CardExpirationYear = encryptedCardExpirationYear;
                    _orderService.UpdateOrder(order);
                }

                //update user information
                //optimization - load only users with PasswordFormat.Encrypted
                var customers = _customerService.GetAllCustomersByPasswordFormat(PasswordFormat.Encrypted);
                foreach (var customer in customers)
                {
                    string decryptedPassword = _encryptionService.DecryptText(customer.Password, oldEncryptionPrivateKey);
                    string encryptedPassword = _encryptionService.EncryptText(decryptedPassword, newEncryptionPrivateKey);

                    customer.Password = encryptedPassword;
                    _customerService.UpdateCustomer(customer);
                }

                securitySettings.EncryptionKey = newEncryptionPrivateKey;
                _settingService.SaveSetting(securitySettings);
                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.EncryptionKey.Changed"));
            }
            catch (Exception exc)
            {
                ErrorNotification(exc);
            }
            return RedirectToAction("GeneralCommon", new { selectedTab = "security" });
        }
        [HttpPost, ActionName("GeneralCommon")]
        [FormValueRequired("togglefulltext")]
        public ActionResult ToggleFullText(GeneralCommonSettingsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var siteScope = this.GetActiveSiteScopeConfiguration(_siteService, _workContext);
            var commonSettings = _settingService.LoadSetting<CommonSettings>(siteScope);
            try
            {
                if (! _fulltextService.IsFullTextSupported())
                    throw new CmsException(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.FullTextSettings.NotSupported"));

                if (commonSettings.UseFullTextSearch)
                {
                    _fulltextService.DisableFullText();

                    commonSettings.UseFullTextSearch = false;
                    _settingService.SaveSetting(commonSettings);

                    SuccessNotification(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.FullTextSettings.Disabled"));
                }
                else
                {
                    _fulltextService.EnableFullText();

                    commonSettings.UseFullTextSearch = true;
                    _settingService.SaveSetting(commonSettings);

                    SuccessNotification(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.FullTextSettings.Enabled"));
                }
            }
            catch (Exception exc)
            {
                ErrorNotification(exc);
            }
            return RedirectToAction("GeneralCommon", new { selectedTab = "fulltext" });
        }




        //all settings
        public ActionResult AllSettings()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();
            
            return View();
        }
        [HttpPost, GridAction(EnableCustomBinding = true)]
        public ActionResult AllSettings(GridCommand command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var settings = _settingService
                .GetAllSettings()
                .Select(x =>
                            {
                                string siteName = "";
                                if (x.SiteId == 0)
                                {
                                    siteName = _localizationService.GetResource("Admin.Configuration.Settings.AllSettings.Fields.SiteName.AllSites");
                                }
                                else
                                {
                                    var site = _siteService.GetSiteById(x.SiteId);
                                    siteName = site != null ? site.Name : "Unknown";
                                }
                                var settingModel = new SettingModel()
                                {
                                    Id = x.Id,
                                    Name = x.Name,
                                    Value = x.Value,
                                    Site = siteName,
                                    SiteId = x.SiteId
                                };
                                return settingModel;
                            })
                .ForCommand(command)
                .ToList();
            
            var model = new GridModel<SettingModel>
            {
                Data = settings.PagedForCommand(command),
                Total = settings.Count
            };
            return new JsonResult
            {
                Data = model
            };
        }
        [GridAction(EnableCustomBinding = true)]
        public ActionResult SettingUpdate(SettingModel model, GridCommand command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            if (model.Name != null)
                model.Name = model.Name.Trim();
            if (model.Value != null)
                model.Value = model.Value.Trim();

            if (!ModelState.IsValid)
            {
                //display the first model error
                var modelStateErrors = this.ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage);
                return Content(modelStateErrors.FirstOrDefault());
            }

            var setting = _settingService.GetSettingById(model.Id);
            if (setting == null)
                return Content("No setting could be loaded with the specified ID");

            var siteId = Int32.Parse(model.Site); //use Site property (not SiteId) because appropriate property is sited in it

            if (!setting.Name.Equals(model.Name, StringComparison.InvariantCultureIgnoreCase) ||
                setting.SiteId != siteId)
            {
                //setting name or site has been changed
                _settingService.DeleteSetting(setting);
            }

            _settingService.SetSetting(model.Name, model.Value, siteId);

            //activity log
            _customerActivityService.InsertActivity("EditSettings", _localizationService.GetResource("ActivityLog.EditSettings"));

            return AllSettings(command);
        }
        [GridAction(EnableCustomBinding = true)]
        public ActionResult SettingAdd([Bind(Exclude = "Id")] SettingModel model, GridCommand command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            if (model.Name != null)
                model.Name = model.Name.Trim();
            if (model.Value != null)
                model.Value = model.Value.Trim();

            if (!ModelState.IsValid)
            {
                //display the first model error
                var modelStateErrors = this.ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage);
                return Content(modelStateErrors.FirstOrDefault());
            }
            var siteId = Int32.Parse(model.Site); //use Site property (not SiteId) because appropriate property is sited in it
            _settingService.SetSetting(model.Name, model.Value, siteId);

            //activity log
            _customerActivityService.InsertActivity("AddNewSetting", _localizationService.GetResource("ActivityLog.AddNewSetting"), model.Name);

            return AllSettings(command);
        }
        [GridAction(EnableCustomBinding = true)]
        public ActionResult SettingDelete(int id, GridCommand command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
                return AccessDeniedView();

            var setting = _settingService.GetSettingById(id);
            if (setting == null)
                throw new ArgumentException("No setting found with the specified id");
            _settingService.DeleteSetting(setting);

            //activity log
            _customerActivityService.InsertActivity("DeleteSetting", _localizationService.GetResource("ActivityLog.DeleteSetting"), setting.Name);

            return AllSettings(command);
        }

        #endregion
    }
}
